import { http } from '@/plugins/axios'
import router from '@/plugins/router'
const storage = useStorage()

export default () => {
  const form = reactive({
    email: 'admin@example.com',
    password: 'password',
  })

  //模型权限验证
  function authorize(userId: undefined | number) {
    return userId == useUserStore().userInfo?.id
  }

  //登录检测
  function isLogin(): boolean {
    return useStorage().get(CacheEnum.TOKEN_NAME)
  }

  //退出登录
  async function logout() {
    await http.request({ url: `auth/logout`, method: 'POST' })
    storage.remove(CacheEnum.TOKEN_NAME)
    router.push({ name: RouteEnum.LOGIN })
  }

  //登录
  const login = useUtil().request(async () => {
    const { data } = await http.request<{ token: string; user: UserModel }>({
      url: `auth/login`,
      method: 'POST',
      data: form,
    })
    storage.set(CacheEnum.TOKEN_NAME, data.token)

    window.$notification?.success({
      title: '登陆成功',
      content: '欢迎回来，' + data.user.name,
      duration: 3000,
    })
    router.push({ name: RouteEnum.HOME })
  })

  //注册
  const register = useUtil().request(async () => {
    try {
      const { data } = await http.request<{ token: string; user: UserModel }>({
        url: `auth/register`,
        method: 'POST',
        data: form,
      })
      storage.set(CacheEnum.TOKEN_NAME, data.token)
      const route = router.resolve({ name: RouteEnum.ADMIN })
      location.href = route.fullPath
    } catch (error) {
      // useCaptcha().getCaptcha()
    }
  })

  return { authorize, isLogin, logout, login, register, form }
}
